#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
"""
@author:apple
@file:start.py
@time:2021/08/30
"""
import os
import shutil
import threading

from flask import Flask, request, render_template, send_from_directory,redirect

app = Flask(__name__)

run_dir = os.path.dirname(__file__)

games = [
    {'id': "1", 'name': '怒火一刀', 'ipas_path': os.path.join(run_dir, "nhyd/ipas"),
     'app_path': os.path.join(run_dir, "nhyd/app")},
    {'id': "2", 'name': '风暴之争', 'ipas_path': os.path.join(run_dir, "fbzz/ipas"),
     'app_path': os.path.join(run_dir, "fbzz/app")}
]

channel_name = "channel"


@app.route("/")
def index():
    ...
    return render_template('index.html', games=games)


@app.route("/show_sub_packet/<game_id>")
def show_sub_packet(game_id):
    ...

    select_game = None

    for game in games:
        if game_id == game['id']:
            select_game = game
            break

    if select_game:
        ...
        ipas_path = select_game['ipas_path']
        packets = []
        if os.path.exists(ipas_path):
            ...
            for name in os.listdir(ipas_path):
                ...
                if name.startswith("pkg-") and name.endswith(".ipa") :
                    packets.append(name)
        return render_template("show_sub_packet.html",
                               game=select_game,
                               packets=packets,
                               game_id=game_id)
    else:
        err_msg = "暂无游戏"
        return render_template("show_error.html", err_msg=err_msg)


@app.route("/ipadown/<game_id>/<pkg_id>")
def ipa_down(game_id, pkg_id):
    ...
    select_game = None

    for game in games:
        if game_id == game['id']:
            select_game = game
            break

    if not select_game:
        ...
        err_msg = "暂无渠道"
        return render_template("show_error.html", err_msg=err_msg)

    ipas_path = select_game['ipas_path']
    packet_path = os.path.join(ipas_path, pkg_id)

    if not os.path.isfile(packet_path):
        err_msg = f'{pkg_id}文件不存在'
        return render_template("show_error.html", err_msg=err_msg)

    return send_from_directory(ipas_path, pkg_id, as_attachment=True)

@app.route("/show_create_packet/<game_id>")
def show_create_packet(game_id):
    ...
    select_game = None

    for game in games:
        if game_id == game['id']:
            select_game = game
            break
    if not select_game:
        ...
        err_msg = "暂无渠道"
        return render_template("show_error.html", err_msg=err_msg)

    return render_template("show_create_packet.html", game=select_game)


@app.route("/delete_packet/<game_id>/<pkg_id>")
def delete_packet(game_id, pkg_id):
    ...
    select_game = None

    for game in games:
        if game_id == game['id']:
            select_game = game
            break
    if not select_game:
        ...
        err_msg = "暂无渠道"
        return render_template("show_error.html", err_msg=err_msg)

    delete_packet_path = os.path.join(select_game['ipas_path'],pkg_id)

    if os.path.exists(delete_packet_path):
        ...
        os.remove(delete_packet_path)

    return redirect("/show_sub_packet/" + game_id)


@app.route("/creat_packet/<game_id>",methods=['POST'])
def create_packet(game_id):
    ...

    select_game = None

    for game in games:
        if game_id == game['id']:
            select_game = game
            break

    if not select_game:
        ...
        err_msg = "暂无渠道"
        return render_template("show_error.html", err_msg=err_msg)

    pkg_id = request.form['pkg_id']

    if not (pkg_id and pkg_id.startswith("pkg-")):
        err_msg = "子包id没有或者格式错误，请使用 pkg-xxxx 这样的格式"
        return render_template("show_error.html", err_msg=err_msg)


    app_path = select_game['app_path']

    payload_path = os.path.join(app_path, "Payload")
    if not os.path.exists(payload_path):
        err_msg = "服务器配置错误，请等待"
        return render_template("show_error.html", err_msg=err_msg)

    game_app_name = None

    for name in os.listdir(payload_path):
        if name.endswith(".app"):
            game_app_name = name
            break

    if not game_app_name:
        err_msg = "服务器配置错误，请等待"
        return render_template("show_error.html", err_msg=err_msg)

    game_app_path = os.path.join(payload_path,game_app_name)
    channel_dir = os.path.join(game_app_path,channel_name)
    if os.path.exists(channel_dir):
        shutil.rmtree(channel_dir)

    last_channel_dir = os.path.join(channel_dir,pkg_id)
    os.makedirs(last_channel_dir)

    #   压缩 payload 目录
    pkg_path = os.path.join(select_game['ipas_path'], pkg_id + ".ipa")
    command = 'cd {};zip -q -r -o {} {}'.format(app_path, pkg_path, "Payload")

    zip_thread = threading.Thread(target=zip_packet, args=(command,))
    zip_thread.start()

    return redirect("/show_sub_packet/" + game_id)


def zip_packet(command):
    ...
    os.system(command)


if __name__ == '__main__':
    pass
    app.run(host='0.0.0.0', debug=False)
